package proxy; /**
 * Copyright (C), 2015-2018, 北京译泰教育科技有限公司
 * FileName: DynamicProxy2
 * Author:   andy
 * Date:     18/1/30 下午5:22
 * Description: ${DESCRIPTION}
 * History:
 */

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * JDK的动态代理<br>
 *
 * @author andy
 * @version V1.0
 * @date 18/1/30 下午5:22
 */
public class DynamicProxy2 implements InvocationHandler {

    private Object target;

    public DynamicProxy2(Object target) {
        this.target = target;
    }

    @SuppressWarnings("uncheck")
    public <T> T getProxy() {
        return (T)Proxy.newProxyInstance(target.getClass().getClassLoader(),
            target.getClass().getInterfaces(), this);
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        before();
        Object result = method.invoke(target, args);
        after();
        return result;
    }

    private void before() {
        System.out.println("before：" + System.currentTimeMillis());
    }

    private void after() {
        System.out.println("after：" + System.currentTimeMillis());
    }

    public static void main(String[] args) {
        DynamicProxy2 dynamicProxy = new DynamicProxy2(new HelloImpl());
        Hello hello = dynamicProxy.getProxy();
        hello.say();

    }

}
